<!--
 * @Description: wiz
 * @Version: 2.0
 * @Autor: wiz
 * @Date: 2022-12-16 21:27:10
 * @LastEditors: swc
 * @LastEditTime: 2024-12-24 09:19:05
-->

<template>
  <div class="main" :class="{ 'is--max': isExpand }">
    <div class="mask-container" v-if="isMask"></div>
    <div class="wy-grid" v-if="isWyGridShow === true">
      <!-- :span="formStyleColumnNum" -->
      <vxe-form
        ref="xForm"
        :loading="loading"
        :items="formColumns"
        :span="formStyleColumnNum"
        :data="localData"
        :class-name="adaptivelayout ? 'is-adaption' : null"
        :rules="validRules"
        @submit="onSubmit"
      >
      </vxe-form>
    </div>
    <Split
      class="panel-split"
      v-model="searchControl.split"
      min="0"
      max="0"
      v-else
    >
      <div class="panel-content" slot="left">
        <div class="wy-grid panel-form">
          <o-toolbar
            v-if="toolbar !== null"
            :config="toolbar"
            @commit-event="commitEvent"
            ref="toolbar"
            :current="pageNo"
            :total="total"
          >
          </o-toolbar>
          <!-- :span="24 / formStyle.columnNum" -->
          <vxe-form
            ref="xForm"
            :loading="loading"
            :items="formColumns"
            :span="formStyleColumnNum"
            :data="localData"
            :rules="validRules"
            @submit="onSubmit"
          >
          </vxe-form>
        </div>
      </div>
      <div class="panel-search" slot="right">
        <div class="panel-search-header">
          <Button
            type="text"
            :title="$srv.getI18nByPath('vxe.toolbar.expand')"
            @click="commitEvent('adjustSearchWidth')"
            ><Icon custom="wy-icon wy-xiangzuo"
          /></Button>
          <Button
            type="text"
            :title="$srv.getI18nByPath('vxe.toolbar.close')"
            @click="commitEvent('closeSearch')"
            ><Icon custom="wy-icon wy-guanbi"
          /></Button>
        </div>
        <div class="panel-search-result" v-if="searchControl.isSearchOpen">
          <o-base-grid
            @on-row-change="handleSearchResultChange"
            ref="searchGrid"
            :config="config"
          ></o-base-grid>
        </div>
      </div>
    </Split>
  </div>
</template>
<script lang="ts">
import { N_input, N_oInteraction } from '@/types';

import { FormItemOptions } from 'vxe-table/types';

import { T_srv, Tsrv, ifs, ts, tvs, vue, T_cmd } from './config';

import vxeConfig from '../configs/vxetable';
import oBaseGrid from '../o-base-grid/index.vue';
import oToolbar from './toolbar.vue';

@T_srv.comp({
  components: {
    oToolbar
  }
})
export default class oBaseForm extends vue {
  @T_srv.prop({
    required: false,
    type: Object,
    default: () => {}
  })
  config: any;

  @T_srv.prop({ default: '' }) readonly parentName?: string;

  @T_srv.prop({ default: '' }) readonly parentFunName?: string;

  @T_srv.prop({ default: 0 }) readonly parentID?: number;

  @T_srv.prop({ default: 0, required: false }) readonly mode!: number;

  @T_srv.prop({ default: false, required: false })
  readonly adaptivelayout!: boolean | string;

  @T_srv.prop({ default: null, required: false }) readonly parentCommand?: any;

  private G_dbType: string = '';

  /**
   * 默认属性
   */
  private defaultFormStyle = {
    columnNum: 4
  };

  private isWyGridShow: boolean = this.mode !== 0;

  /**
   * 表格属性
   */
  public form: any = null;

  // form实例
  private searchGrid: any = null;

  private name: string | null = null;

  // form的表名
  private funName: string | null = null;

  private formID: string | null = null;

  private formStyle: { columnNum: number };

  private formStyleColumnNum: number = this.defaultFormStyle.columnNum;

  // form的样式
  // public formColumns: Array<ifs.vxeTableTypes.FormItemOptions> = [];
  public formColumns: any = [];

  // form的column
  private formFields: any = [];

  // form的字段
  private validRules: any = null;

  // 表验证
  public tbar!: oToolbar;

  private toolbar: any = null;

  // table的toolbar
  private listenType: string = 'default';

  // 监听类型
  private isExpand: boolean = false;

  /**
   * 控制属性
   */
  private loading: boolean = false;

  // 是否正在加载
  private isIndependent: boolean = true;

  // 是否为独立状态（无父组件）
  private isEditable = false;

  private pageNo: number = 1;

  // 页数
  private total: number = 0; // 总页

  private Tcmd: T_cmd = undefined;

  public localData: any = {
    // name: 'test1',
    // nickname: 'Testing',
    // sex: '',
    // age: 26,
    // date: null,
    // address: '左右布局'
  };

  // 本地数据
  public cloudData: any = {}; // 云数据

  private isNew: boolean = false;

  private searchControl: any = {};

  /**
   * 数据
   */
  private current: any = {
    columnIndex: 0,
    column: {}
  };

  private initFilter: any = [];

  private pidSetting: any = {};

  private subQueryArr: string[] = [];

  public isMask: boolean = false;

  /* 父组件compBoxInfo */
  @T_srv.prop({
    required: false,
    type: Object,
    default: null
  })
  compBoxInfo: ifs.I_compBoxInfo;

  /* 组件名 */
  private G_compName: string = 'oBaseForm';

  /* 组件箱信息对象 */
  private GT_compBoxInfo: ifs.I_compBoxInfo;

  /* 组件箱对象 */
  private GT_compBox: ifs.I_compBox;

  /* 组件箱识别ID */
  private G_compID: string;

  created() {
    this.init(this.config);
    // 如果父组件没有传参，那就产生一个
    this.GT_compBoxInfo = Tsrv.getCompInfo(this.compBoxInfo);
    this.G_compID = this.GT_compBoxInfo.compID;
    this.GT_compBox = this.GT_compBoxInfo.TcompBox;
    this.Tcmd = new T_cmd(this, this.GT_compBoxInfo);
    // this.Tcmd.init(this, this.GT_compBoxInfo);
  }

  mounted() {
    this.G_compName = this.G_compName;
    this.GT_compBox.addCompMergeName(this.G_compID, this.G_compName, this);
    this.$emit('compBoxInfo', this.GT_compBoxInfo);
    this.$emit('mounted', this);

    this.form = this.$refs.xForm;
    this.tbar = this.$refs['toolbar'] as oToolbar;
    this.setVxeFormStyleVariable();
    if (!Tsrv.utils.isEmpty(this.parentName)) {
      this.isIndependent = false;
      this.name = this.parentName;
      this.funName = this.parentFunName;
    }
    if (this.isIndependent) {
      const that = this;
      if (this.listenType === 'default') {
        this.$bus.$on(this.funName, (msg: any) => {
          if (msg.listenType === that.listenType) that.handleListener(msg);
        });
      }
      // else {
      //   this.$mbus.$on(this.funName, (msg: any) => {
      //     if (msg.listenType === that.listenType) that.handleListener(msg);
      //   });
      // }
      this.loadData();
    }
  }

  destroyed() {
    /* 注册组件销毁 */
    this.GT_compBox.removeCompMergeName(this.G_compID, this.G_compName);

    /* 最终应用组件销毁 */
    /* this.GT_compBox.removeCompMergeName(this.G_compID, this.G_compName,'funName'); */

    /* 如果父组件传入的compBoxInfo则删除本文件产生的引用,反之是本组件产生的ID统一删除 */
    if (Tsrv.utils.isEmpty(this.compBoxInfo)) {
      this.GT_compBox.removeCompsWithCompID(this.G_compID);
    } else {
      this.GT_compBox.removeCompsMergeName(this.G_compID, [
        `'${this.G_compName}'`
      ]);
    }

    /* 如果是动态组件可能会关闭全局compBox */
    // this.GT_compBox = null
  }

  private openSearch() {
    setTimeout(() => {
      this.searchGrid = this.$refs.searchGrid as oBaseGrid;
      this.searchGrid.setToolbarStatus('insert', 'isShow', false);
      this.searchGrid.setToolbarStatus('delete', 'isShow', false);
      this.searchGrid.setToolbarStatus('edit', 'isShow', false);
      this.searchGrid.setToolbarStatus('save', 'isShow', false);
      this.searchGrid.setToolbarStatus('import', 'isShow', false);
      this.searchGrid.setToolbarStatus('export', 'isShow', false);
      this.searchGrid.setToolbarStatus('print', 'isShow', false);
    }, 0);
  }

  private handleListener(msg: any) {
    switch (msg.type) {
      case 'search':
        this.handleResponseSearch(msg);
        break;

      default:
        break;
    }
  }

  private handleResponseSearch(msg: any) {
    const id = msg.content.val[0] as string;
    if (id) {
      if (id !== this.formID) {
        this.getRecordIndexById(id).then((index: number) => {
          if (index) {
            this.jumpTo(index);
          }
        });
      }
    } else {
      this.$msg(Tsrv.getI18nByPath('warm.noCorresData'));
    }
  }

  private loadData(pageNo = 1) {
    return new Promise(resolve => {
      this.loadFormData(pageNo).then((data: any) => {
        this.toolbar.insert.isDisable = false;
        this.toolbar.edit.isDisable = false;
        this.toolbar.edit.value = false;
        this.toolbar.refresh.isDisable = false;
        this.updateSaveBtnStatus();
        this.pageNo = pageNo;
        if (this.pageNo === 1) {
          this.toolbar.next.isDisable = false;
          this.toolbar.jumpLast.isDisable = false;
        }

        if (data.rows && data.rows.length > 0) {
          this.isNew = false;
          this.setFormData(data.rows[0]);
          resolve(data.rows);
        } else {
          resolve(false);
          this.insert();
        }
      });
    });
  }

  private save() {
    if (this.isNew) {
      const fv = this.getData() as ifs.I_fv[];
      const t = new ts.T_ctdInsRec();
      t.setScope({}).setBaseDataGeneral({} as ifs.I_rule, {}, ...fv);
      Tsrv.addRows(this.name, this.G_dbType, {} as ifs.I_rule, t).then(r => {
        const [b, res, msg] = r;
        this.$msg(msg);
        if (b) {
          this.loadData();
        }
      });
    }
  }

  private insert() {
    if (!this.isNew) {
      this.isNew = true;
      this.formID = null;
      this.pageNo = 0;

      // toolbar设置
      this.toolbar.delete.isDisable = false;
      this.toolbar.next.isDisable = true;
      this.toolbar.jumpLast.isDisable = true;
      this.toolbar.previous.isDisable = true;
      this.toolbar.jumpFirst.isDisable = true;
      this.toolbar.insert.isDisable = true;
      this.toolbar.edit.isDisable = true;
      this.toolbar.refresh.isDisable = true;

      this.toolbar.save.isDisable = false;

      // 可编辑
      this.setModify(true);

      // 清空数据
      this.clearFormData();
    }
  }

  public getRecordIndexById(id: string) {
    return new Promise((resolve, reject) => {
      let sql = '';
      if (this.initFilter.length > 0) {
        sql = ' and';
        this.initFilter.forEach(el => {
          sql += ` ${el.field} = ${el.value}`;
        });
      }
    });
  }

  private handleSearchResultChange(data: any) {
    if (data.data.to) {
      data = data.data.to.row;
      if (data.id) {
        if (data.id !== this.formID) {
          this.getRecordIndexById(data.id).then((index: number) => {
            if (index) {
              this.jumpTo(index);
            }
          });
        }
      }
    }
  }

  /**
   * 初始化
   */
  public init(config: any) {
    this.G_dbType = config?.dbType;
    if (this.mode === 0) {
      this.isWyGridShow = false;
      this.isIndependent = true;
      this.name = config.name;
      this.funName = config.name;

      this.listenType = this.config['listenType'] || 'default';

      this.formStyle = config.formStyle;
      this.formStyleColumnNum = 24 / this.formStyle.columnNum;
      this.validRules = this.getValidRules(config.formColumns);
      this.formColumns = this.transformColumns(config.formColumns);

      this.toolbar = vxeConfig.getToolbarConfig(config.toolbar, 'baseform');

      const toolbarPermission = Tsrv.utils.find(
        config.permission,
        el =>
          el.area === 'toolbar' &&
          (el.type === 'button' || el.type === 'NULL') &&
          el.data.insert !== undefined
      );
      if (toolbarPermission) {
        const data = toolbarPermission.data;
        for (const key in this.toolbar) {
          if (data[key]) {
            this.toolbar[key].auth = !!data[key];
          }
        }
      }

      // 权限控制表格列
      const tablePermission = Tsrv.utils.find(
        config.permission,
        el => el.area === 'table'
      );
      if (tablePermission) {
        const data = tablePermission.data;

        for (const item in data) {
          const key = Tsrv.utils.find(
            config.tableColumns,
            el => el.field === item
          );
          if (key && !!data[item] === false) {
            key.isShow = false;
          }
        }
      }

      this.toolbar.previous.isDisable = true;
      this.toolbar.jumpFirst.isDisable = true;
    } else if (this.mode === 2) {
      this.isWyGridShow = true;
      this.isIndependent = false;
      this.formStyle = config ? config.formStyle : this.defaultFormStyle;
      this.formStyleColumnNum = 24 / this.formStyle.columnNum;
      if (config) {
        this.validRules = this.getValidRules(config.formColumns);
        this.formColumns = this.transformColumns(config.formColumns);
      }
    } else {
      this.isIndependent = false;
      // this.formStyle = this.defaultFormStyle;
      this.validRules = {};
    }
  }

  /**
   * 跳页
   */
  private jump(pos) {
    if (pos === null && this.pageNo !== this.total) {
      this.pageNo = this.total;
      this.toolbar.next.isDisable = false;
      this.toolbar.jumpLast.isDisable = false;
      this.toolbar.previous.isDisable = true;
      this.toolbar.jumpFirst.isDisable = true;
      this.loadFormData(this.pageNo).then(res => {
        if (res !== undefined) this.loadData(this.pageNo);
      });
    } else if (pos === -1 && this.pageNo !== 1) {
      this.pageNo = 1;
      this.toolbar.next.isDisable = true;
      this.toolbar.jumpLast.isDisable = true;
      this.toolbar.previous.isDisable = false;
      this.toolbar.jumpFirst.isDisable = false;
      this.loadFormData(this.pageNo).then(res => {
        if (res !== undefined) this.loadData(this.pageNo);
      });
    } else if (pos > 1 && pos < this.total) {
      this.pageNo = pos;
      this.toolbar.next.isDisable = false;
      this.toolbar.jumpLast.isDisable = false;
      this.toolbar.previous.isDisable = false;
      this.toolbar.jumpFirst.isDisable = false;
      this.loadFormData(this.pageNo).then(res => {
        if (res !== undefined) this.loadData(this.pageNo);
      });
    }
  }

  public commitEvent(val: string, params: any = null) {
    switch (val) {
      // 第一行插入并激活
      case 'edit':
        this.setModify(params);
        break;
      case 'save':
        this.save();
        break;
      case 'reload':
        this.loadData(this.pageNo).then(res => {
          if (res) {
            this.$msg('50003,FE,0,');
          }
        });
        break;
      case 'expand':
        this.isExpand = !!params;
        break;
      case 'search':
        this.searchControl.isSearchOpen = !this.searchControl.isSearchOpen;
        this.searchControl.split = this.searchControl.isSearchOpen ? 0.6 : 1;
        if (this.searchControl.isSearchOpen) this.openSearch();
        break;
      case 'insert_actived':
        this.insert();
        break;
      case 'remove':
        this.delete();
        break;
      case 'adjustSearchWidth':
        this.searchControl.split = this.searchControl.isSearchFullOpen
          ? 0.6
          : 0;
        this.searchControl.isSearchFullOpen = !this.searchControl
          .isSearchFullOpen;
        break;
      case 'prevRecord':
        this.prev();
        break;
      case 'nextRecord':
        this.next();
        break;
      case 'firstRecord':
        this.start();
        break;
      case 'lastRecord':
        this.end();
        break;
      case 'jumpToPage':
        this.jumpTo(Tsrv.utils.toNumber(params.target.value));
        break;
      case 'closeSearch':
        this.searchControl.isSearchOpen = false;
        this.searchControl.split = 1;
        this.searchControl.isSearchFullOpen = false;
        break;

      default:
        break;
    }
  }

  private doDelete() {
    return new Promise((resolve, reject) => {
      if (this.formID) {
        const filter = JSON.parse(`{"id":{"$in":[${this.formID}]}}`);
        const ctdDel = new ts.T_ctdDelRec();
        ctdDel.setFilter(filter).setRule({} as ifs.I_rule);
        Tsrv.delRows(this.name, this.G_dbType, {} as ifs.I_rule, ctdDel).then(
          r => {
            const [b, res, msg] = r;
            this.$msg(msg);
            if (b) {
              this.loadData();
              resolve(true);
            } else {
              reject();
            }
          }
        );
      } else {
        reject();
      }
    });
  }

  private beforeDelete() {
    if (this.isNew) {
      this.pageNo = 1;
      this.loadData();
    } else {
      if (this.loading === false) {
        this.loading = true;
        const msg = this.$Message.loading({
          content: Tsrv.getI18nByPath('prompt.deleting') as string,
          duration: 0
        });

        this.doDelete()
          .then(() => {
            this.loading = false;
            // @ts-ignore
            msg();
          })
          .catch(() => {
            this.loading = false;
            // @ts-ignore
            msg();
          });
      }
    }
  }

  private delete() {
    this.$Modal.confirm({
      title: Tsrv.getI18nByPath('prompt.isDeleteData') as string,
      content: Tsrv.getI18nByPath('prompt.isDeleteData') as string,
      onOk: () => {
        this.beforeDelete();
      }
    });
  }

  /**
   * 设置是否可编辑
   */
  public setModify(value: boolean) {
    this.isEditable = value;
    this.formColumns.forEach(el => {
      if (el.itemRender && el.itemRender.props) {
        el.itemRender.props.disabled =
          el.itemRender.props.initDisabled || !value;
      }
    });
  }

  /**
   * 验证输入
   */
  public validate() {
    return this.form.validate();
  }

  /**
   * 清除验证
   */
  public clearValidate() {
    this.form.clearValidate();
  }

  /**
   * 设置列数
   */
  public setColumnNumber(number: number, force: boolean = false) {
    // this.formStyle.columnNum = number;
    this.formStyleColumnNum = number;
    // this.formStyleColumnNum = 24 / this.formStyle.columnNum;
    this.formStyleColumnNum = 24 / this.formStyleColumnNum;
    if (force && this.formColumns) {
      this.formColumns.forEach(el => {
        el.span = 24 / number;
      });
    }
  }

  /**
   * 设置样式
   */
  public setStyle(config) {
    this.formStyle = config;
    this.formStyleColumnNum = 24 / this.formStyle.columnNum;
  }

  /**
   * 设置字段
   */
  public setColumns(columns) {
    const data = Tsrv.utils.clone(columns, true);
    for (const key in data) {
      if (!data[key].itemRender.props) {
        data[key].itemRender.props = {};
      }
      data[key].span = data[key].span || 24;
      data[key].itemRender.props.disabled = false;
      // 表格中字段设置禁止输入，多表表单字段应该也禁止输入
      // data[key].itemRender.props.initDisabled = false;

      data[key].itemRender.events = {};
      data[key].itemRender.events['on-focus'] = this.listenFieldEvent;
      data[key].itemRender.events['on-blur'] = this.listenFieldEvent;
      data[key].itemRender.events['on-change'] = this.listenFieldEvent;
      data[key].itemRender.events['on-dochange'] = this.listenDoChange;
    }
    this.formColumns = data;
  }

  /**
   * 获取数据
   */
  public getData() {
    let data: any = {};
    this.formColumns.forEach(el => {
      let field = el.field;
      if (el.field.indexOf('|') > -1) {
        field = el.field.split('|')[1];
      }
      if (!Tsrv.utils.find(this.subQueryArr, item => item === field)) {
        data[field] = null;
      }
    });
    for (const key in this.localData) {
      if (this.formFields.indexOf(key) > -1 && data[key] !== undefined) {
        data[key] = this.localData[key];
      }
    }
    if (Tsrv.utils.isEmpty(data)) {
      data = [];
    } else {
      data = Tsrv.utils.objToArr(data, 'field', 'value', {
        // ignore: ['_XID', '_file_'],
        ignore: ['_XID', '_file_info_id_'],
        ignoreRegex: ['|', '/']
      });
    }
    return data;
  }

  public getDbType(): string {
    return this.G_dbType;
  }

  private updateSaveBtnStatus() {
    const changes = this.getUpdateData();
    if (changes) this.toolbar.save.isDisable = changes.length === 0;
  }

  /**
   * 设置更新数据
   */
  // eslint-disable-next-line consistent-return
  public getUpdateData(withID: boolean = false): ifs.I_fv[] {
    if (this.formID !== null) {
      let update: any = {};
      for (const key in this.localData) {
        if (
          this.formFields.indexOf(key) > -1 &&
          this.localData[key] !== this.cloudData[key] &&
          !Tsrv.utils.find(this.subQueryArr, item => item === key)
        ) {
          update[key] = this.localData[key];
        }
      }
      if (Tsrv.utils.isEmpty(update)) {
        update = [];
      } else {
        if (withID) update['id'] = this.formID;
        update = Tsrv.utils.objToArr(update, 'field', 'value', {
          // ignore: ['_XID', '_file_'],
          ignore: ['_XID', '_file_info_id_'],
          ignoreRegex: ['|', '/']
        });
      }
      return update;
    }
  }

  /**
   * 获取过滤数据
   */
  public getFilterData(options?: {
    hasEmpty?: boolean;
    realValue?: boolean;
    hasM2o?: boolean;
  }) {
    const items = this.formColumns;
    const data = this.form.data;

    const formData = [];
    for (let i = 0; i < items.length; i++) {
      let field = items[i].field;
      const type = items[i].itemRender.name;
      if (field) {
        let value = data[field] || '';
        if (options?.hasEmpty || value !== '') {
          if (type === 'oDatePicker') {
            if (!options?.realValue) {
              if (value.indexOf(' - ') > -1) {
                value = value.split(' - ');
              }
            }
          } else if (type === 'oM2oSelector') {
            if (options?.hasM2o) {
              const a = {
                field,
                value
              };
              if (items[i].params && items[i].params.table && value) {
                a['tableName'] = items[i].params.table;
              }
              formData.push(a);
            }
            field = field.split('|')[1];
            if (!options?.realValue) {
              value = data[field];
            }
          } else if (type === 'oNumberInputRange') {
            if (value[0] !== null && value[1] !== null) {
              value = `${value[0]}:${value[1]}`;
            } else if (value[0] === null && value[1] !== null) {
              value = value[1];
            } else if (value[0] !== null && value[1] === null) {
              value = value[0];
            } else {
              continue;
            }
          }

          if (items[i].params && items[i].params.table && value) {
            formData.push({
              field,
              value,
              tableName: items[i].params.table
            });
            continue;
          }

          if (value) {
            formData.push({
              field,
              value
            });
          }
        }
      }
    }
    return formData;
  }

  /**
   * 设置字段值
   */
  public setFieldValue(property: string, value: any) {
    // const formItems = this.form.$children;
    const formItems = this.form.getItems();
    this.localData[property] = value;
    for (let i = 0; i < formItems.length; i++) {
      if (formItems[i].field === property) {
        const el = formItems[i];
        const name = el.itemRender.name;
        // const name = el?.itemConfig?.itemRender?.name;
        if (!name) continue;
        // if (el.$children[0]) {
        //   if (name === 'oI18nSelector') {
        //     (el.$children[0] as oI18nSelector).setValue(value);
        //   } else if (name === 'oDatePicker') {
        //     (el.$children[0] as oDatePicker).setValue(value);
        //   } else if (name === 'oNumberInput') {
        //     (el.$children[0] as oNumberInput).setValue(value);
        //   } else if (name === 'oM2oSelector') {
        //     (el.$children[0] as oM2oSelector).setValue(value);
        //   } else if (name === 'oInput') {
        //     (el.$children[0] as oInput).setValue(value);
        //   } else if (name === 'oSelect') {
        //     (el.$children[0] as oSelect).setValue(value);
        //   } else if (name === 'oSwitch') {
        //     (el.$children[0] as oSwitch).setValue(value);
        //   }
        // }
        let o = this.GT_compBox.getCompMergeName(this.G_compID, property);
        if (!o) {
          o = this.findCompInstance(property, name);
        }
        if (o) {
          if (name === 'oI18nSelector') {
            o.setValue(value);
          } else if (name === 'oDatePicker') {
            o.setValue(value);
          } else if (name === 'oNumberInput') {
            // (el.$children[0] as N_input.oNumberInput).setValue(value);
            o.setValue(value);
          } else if (name === 'oM2oSelector') {
            (el.$children[0] as N_input.oM2oSelector).setValue(value);
          } else if (name === 'oInput') {
            if (el.$children) {
              (el.$children[0] as N_input.oInput).setValue(value);
            } else {
              o.setValue(value);
            }
          } else if (name === 'oSearch') {
            if (el.$children) {
              (el.$children[0] as N_input.oSearch).setValue(value);
            } else {
              o.setValue(value);
            }
          } else if (name === 'oSelect') {
            // (el.$children[0] as N_input.oSelect).setValue(value);
            o.setValue(value);
          } else if (name === 'oSwitch') {
            // (el.$children[0] as N_input.oSwitch).setValue(value);
            if (el.$children) {
              (el.$children[0] as N_input.oSwitch).setValue(value);
            } else {
              o.setValue(value);
            }
          }
        }
        break;
      }
    }
  }

  // 寻找组件实例并加进组件箱
  public findCompInstance(property: string, compName: string): any {
    // this.form.$children[4].itemConfig.itemRender.name
    // this.form.$children[4].itemConfig.field
    const childrens = this.form.$children;
    for (let i = 0; i < childrens.length; i++) {
      const _compName = childrens[i]?.itemConfig?.itemRender?.name;
      const _compField = childrens[i]?.itemConfig?.field;
      if (_compName === compName && _compField === property) {
        const o = childrens[i].$children[0] || undefined;
        if (!this.GT_compBox.getCompMergeName(this.G_compID, property) && o) {
          this.GT_compBox.addCompMergeName(this.G_compID, property, o);
        }
        return o;
      }
    }
    return undefined;
  }

  /**
   * 清除表数据
   */
  public clearFormData() {
    const that = this;
    return new Promise(resolve => {
      if (that?.form?.items) {
        const existFields = that.form.items.map(el => el.field);
        for (const key in that.form.data) {
          if (Tsrv.utils.find(existFields, el => el.indexOf(key) > -1)) {
            that.form.data[key] = null;
            that.localData[key] = null;
          }
        }
        const formItems = that.form.$children;
        for (let i = 0; i < formItems.length; i++) {
          const el = formItems[i];
          // const name = el.itemRender.name;
          const name = el?.itemConfig?.itemRender?.name;
          if (!name) continue;
          if (name === 'oI18nSelector') {
            (el.$children[0] as N_input.oI18nSelector).resetValue();
          } else if (name === 'oDatePicker') {
            (el.$children[0] as N_input.oDatePicker).resetValue();
          } else if (name === 'oNumberInput') {
            (el.$children[0] as N_input.oNumberInput).resetValue();
          } else if (name === 'oM2oSelector') {
            (el.$children[0] as N_input.oM2oSelector).resetValue();
          } else if (name === 'oInput') {
            (el.$children[0] as N_input.oInput).resetValue();
          } else if (name === 'oSearch') {
            (el.$children[0] as N_input.oSearch).resetValue();
          } else if (name === 'oSelect') {
            (el.$children[0] as N_input.oSelect).resetValue();
          } else if (name === 'oNumberInputRange') {
            (el.$children[0] as N_input.oNumberInputRange).resetValue();
          } else if (name === 'input') {
            el.$el.querySelector('input').value = null;
          }
          if (that.pidSetting[el.field]) {
            that.setFieldValue(el.field, that.pidSetting[el.field]);
          }
        }
      }
      resolve(true);
    });
  }

  /**
   * 设置表数据
   */
  public setFormData(row: { [key: string]: any }) {
    row = row || {};
    this.clearFormData().then(() => {
      const that = this;
      this.$nextTick().then(() => {
        if (row.id) that.formID = row.id;
        that.cloudData = Tsrv.utils.clone(row, true);
        that.localData = row;
      });
    });
  }

  public addInitFilter(
    field:
      | string
      | { field: string; value: string | number | null }
      | { field: string; value: string | number | null }[],
    value: string | number | null = null
  ) {
    // eslint-disable-next-line no-shadow
    const add = (field: string, value: string | number | null) => {
      const find = Tsrv.utils.find(this.initFilter, el => el.field === field);
      if (find) {
        if (value !== '' && value !== null) {
          find.value = Tsrv.utils.toString(value);
        } else {
          Tsrv.utils.remove(this.initFilter, el => el.field === field);
        }
      } else {
        if (value !== '' && value !== null) {
          this.initFilter.push({
            field,
            value: Tsrv.utils.toString(value)
          });
        }
      }
    };
    if (Tsrv.utils.isString(field)) {
      add(field as string, value);
    } else if (Tsrv.utils.isPlainObject(field)) {
      field = Tsrv.utils.clone(field, true) as {
        field: string;
        value: string | number | null;
      };
      add(field.field, field.value);
    } else if (Tsrv.utils.isArray(field)) {
      field = Tsrv.utils.clone(field, true) as {
        field: string;
        value: string | number | null;
      }[];
      field.forEach(el => {
        add(el.field, el.value);
      });
    }
  }

  /**
   * 加载表数据
   */
  public loadFormData(
    pageNo: number = 1,
    filter?: ifs.I_fv[]
  ): Promise<ifs.I_queryResData<any>> {
    return new Promise(resolve => {
      if (!Tsrv.utils.isEmpty(this.name)) {
        if (Tsrv.utils.isEmpty(filter)) {
          filter = this.initFilter;
        } else {
          filter = this.initFilter.concat(filter);
        }
        const gpd = new ts.T_getPartDataArg();
        const f = new ts.T_filter();
        gpd.setFunName(this.name);
        gpd.setLang(this.$i18n.locale || 'en-US');
        gpd.setPage(pageNo, 1).setDbType(this.G_dbType);
        gpd.setFilter(f.parseFvs(filter));
        gpd.setSort([
          { field: 'id', value: tvs.V_sortValue.DESC }
        ] as ifs.I_sort[]);
        this.loading = true;
        Tsrv.getData<any, ifs.I_getPartDataArg>(gpd).then(
          ([b, res, rows, msg]) => {
            this.loading = false;
            if (b) {
              if (rows.length > 0 && this.isIndependent) {
                this.formID = rows[0].id;
                this.cloudData = Tsrv.utils.clone(rows[0], true);
                for (const key in rows[0]) {
                  this.localData[key] = rows[0][key];
                }
              }
              this.total = res.data.total;
              resolve(res.data);
            } else {
              this.$msg(msg);
              resolve(undefined);
            }
          }
        );
      } else {
        resolve(undefined);
      }
    });
  }

  /**
   * 提交表单
   */
  private onSubmit(e: any) {
    this.$emit('submit', e);
  }

  /**
   * 转换验证规则
   */
  private getValidRules(columns: any) {
    const rules: any = {};
    columns.forEach((el: any) => {
      rules[el.field] = [
        {
          required: !!el.required,
          message: Tsrv.getI18nByPath('warm.mustFill')
        }
      ];
    });
    return rules;
  }

  /**
   * 处理column
   */
  public transformColumns(columns: any): FormItemOptions[] {
    const vxeColumns: Array<FormItemOptions> = [];
    this.formFields = [];
    columns.forEach((el: any, idx: number) => {
      this.formFields.push(el.field);
      if (!this.localData[el.field]) this.localData[el.field] = null;
      vxeColumns.push(this.getClmsWithConfig(el, idx));
    });

    vxeColumns.push({
      field: '_file_info_id_',
      folding: true,
      title: '_file_info_id_',
      itemRender: {
        name: 'input'
      },
      rules: null
    });
    this.formFields.push('_file_info_id_');
    return vxeColumns;
  }

  private getClmsWithConfig(e: any, index: number) {
    let field = e.field;
    const column: any = {
      field,
      align: 'left',
      folding: !e.isShow,
      params: {},
      title:
        e.comment !== '' && e.comment !== null
          ? // ? Tsrv.getI18nBySrv(e.comment)
            // : Tsrv.getI18nBySrv(e.field)
            e.comment
          : e.field
    };
    column.itemRender = {
      name: '',
      props: {
        size: 'small',
        disabled: !!e.disabled || !this.isEditable,
        placeholder: e.placeholder ?? '',
        initDisabled: !!e.disabled,
        cascadeFilter: e.cascadeFilter
      },
      autoselect: true,
      events: {},
      attrs: {}
    };

    let isM2o = false;
    let isSelection = false;
    if (
      e.many2one &&
      e.many2one !== '' &&
      e.many2one.toTable !== '' &&
      e.many2one.toTable !== null
    ) {
      const m2o = Tsrv.utils.getM2OConfig(e.many2one);
      column.itemRender.props['m2oConfig'] = m2o;
      column.itemRender.props['isDropdown'] = !!m2o.isDropdown;
      isM2o = true;
      let flag = true;
      for (let i = 0; i < m2o.fields.length; i++) {
        if (m2o.fields[i].isReturn === true) {
          flag = false;
          break;
        }
      }
      if (flag) {
        field = `m2o|${e.field}|${m2o.toTable}|${m2o.toField}`;
        column.field = field;
        this.validRules[field] = this.validRules[e.field];
      }
      if (!this.localData[field]) this.localData[field] = null;
    } else if (e.selectionID && e.selectionID !== null) {
      const slcField = `slc|${e.field}|${e.selectionID}`;
      isSelection = true;
      this.validRules[slcField] = this.validRules[e.field];
    } else if (!Tsrv.utils.isEmpty(e.subQuery)) {
      this.subQueryArr.push(field);
      column.itemRender.props.disabled = true;
    }

    if (e.defaultFilter) {
      column.params.isDefaultFilter = true;
    }

    if (e.minWidth && e.minWidth !== '') {
      const span = Tsrv.utils.toNumber(e.minWidth);
      if (span >= 1 && span <= 24) {
        column.span = span;
      }
    }

    // 初始过滤
    if (e.initFilter && e.initFilter !== '') {
      this.addInitFilter(e.field, e.initFilter);
      this.pidSetting[field] = e.initFilter;
    }

    column.align = e.align || 'left';
    if (e.type) {
      // 获取数据类型和长度
      let length = e.type.match(/\(([^)]*)\)/);
      let type = e.type.toLowerCase();
      // 当redioOptions有配置，form则忽略type来配置itemRender
      // radioOptions:N_oInteraction.I_radioOpt
      const radioOptions = e?.radioOptions;
      const formatType: string = '';
      if (length != null) {
        type = type.replace(/\(.*?\)/, '');
        length = length[1];
      }
      // 整合类型
      if (
        type === 'int' ||
        type === 'dec' ||
        type === 'decimal' ||
        type === 'smallint'
      ) {
        type = 'number';
      } else if (
        type === 'varchar' ||
        type.indexOf('text') > -1 ||
        type === 'bigint' ||
        type === 'json'
      ) {
        type = 'text';
      } else if (type === 'bit') {
        type = 'boolean';
      }
      // if (Tsrv.utils.get(e.formatter, 'type') === 'i18n') {
      //   type = 'i18n';
      // }
      if (!Tsrv.noValue(e.formatter?.type)) {
        const formatterType = e.formatter.type;
        if (formatterType === 'i18n') {
          type = 'i18n';
        } else if (formatterType === 'file') {
          type = 'file';
        } else if (formatterType === 'image') {
          type = 'image';
        } else if (formatterType === 'color') {
          type = 'color';
        } else if (formatterType === 'richText') {
          type = 'richText';
        } else if (formatterType === 'control') {
          type = 'control';
        }
      }
      if (isM2o) {
        type = 'm2o';
      } else if (isSelection) {
        type = 'selection';
      }

      if (e.actions) {
        // column.itemRender.attrs['actions'] = {};
        // if (e.actions.dochange) {
        //   column.itemRender.attrs['actions'].dochange = e.actions.dochange;
        // }
        column.itemRender.attrs['actions'] = [];
        column.itemRender.attrs['actions'] = e.actions;
      }
      // 当前组件控制类
      column.itemRender.props['getTcommand'] = () =>
        Tsrv.noValue(this.parentCommand) ? this.Tcmd : this.parentCommand;
      column.itemRender.events['on-focus'] = this.listenFieldEvent;
      column.itemRender.events['on-blur'] = this.listenFieldEvent;
      column.itemRender.events['on-change'] = this.listenFieldEvent;
      column.itemRender.events['on-dochange'] = this.listenDoChange;
      // column.itemRender.events['on-enter'] = this.listenFieldEvent; // baseForm有自己的出车操作
      column.itemRender.events['on-mouseleave'] = this.listenFieldEvent;
      column.itemRender.events['on-mouseenter'] = this.listenFieldEvent;
      switch (formatType) {
        case 'number':
          column.itemRender.props['type'] = 'number';
          column.formatter = ['numberFormatter', e.formatter];
          break;
        case 'i18n':
          column.formatter = 'i18nFormatter';
          break;
        default:
          break;
      }
      // 当redioOptions有配置，form则忽略type来配置itemRender
      //
      if (!Tsrv.utils.noValue(radioOptions)) {
        column.itemRender.name = 'oRadio';
        column.itemRender.props['options'] = radioOptions;
        column.itemRender.props['radioArrang'] = e?.radioArrang;
      } else {
        switch (type) {
          case 'number':
            column.itemRender.name = 'oNumberInput';
            break;
          case 'boolean':
            column.itemRender.name = 'oSwitch';
            break;
          case 'text':
            if (e.formatter.type === 'icon') {
              column.itemRender.name = 'oIconbox';
            } else {
              column.itemRender.name = 'oInput';
            }
            break;
          case 'datetime':
            column.itemRender.name = 'oDatePicker';
            column.itemRender.props['type'] = 'datetime';
            column.itemRender.props['format'] = 'yyyy-MM-dd HH:mm:ss';
            column.itemRender.props['dataFormat'] =
              length === 3 ? 'yyyy-MM-dd HH:mm:ss.SSS' : 'yyyy-MM-dd HH:mm:ss';
            break;
          case 'date':
            column.itemRender.name = 'oDatePicker';
            column.itemRender.props['type'] = 'date';
            column.itemRender.props['format'] = 'yyyy-MM-dd';
            column.itemRender.props['dataFormat'] = 'yyyy-MM-dd';
            break;
          case 'time':
            column.itemRender.name = 'oDatePicker';
            column.itemRender.props['type'] = 'time';
            column.itemRender.props['format'] = 'HH:mm:ss';
            column.itemRender.props['dataFormat'] = 'HH:mm:ss';
            break;
          case 'm2o':
            column.itemRender.name = 'oM2oSelector';
            break;
          case 'i18n':
            column.itemRender.name = 'oI18nSelector';
            break;
          case 'selection':
            column.itemRender.name = 'oSelect';
            column.itemRender.props['optionId'] = e.selectionID;
            break;
          // 新添加
          case 'file':
            column.itemRender.name = 'oFileInput';
            break;
          case 'image':
            column.itemRender.name = 'oImageSelector';
            column.itemRender.props['imgHeight'] =
              column.params.imgHeight === undefined &&
              column.params.imgHeight === 1
                ? '120px'
                : `${column.params.imgHeight}px`;
            break;
          case 'color':
            column.itemRender.name = 'oColorSelector';
            break;
          case 'richText':
            column.itemRender.name = 'oRichText';
            break;
          case 'control':
            column.itemRender.name = 'oControl';
            break;
          // 多选框，适用于数组类型 （目前适用于前端交互funpanel）
          case 'multiselection':
            column.itemRender.name = 'oMultiSelector';
            column.itemRender.props['multiOptions'] = e.multiOptions;
            break;

          default:
            break;
        }
      }
    }

    // if (e.hasOwnProperty('isI18n')) {
    if (Object.prototype.hasOwnProperty.call(e, 'isI18n')) {
      column.itemRender.props['isI18n'] = e.isI18n;
    }

    if (e.span) {
      column.span = e.span;
    }
    // column.itemRender.props['getTcommand'] = () => this.Tcmd;
    return column;
  }

  /**
   * 监听聚焦
   */
  private listenFocus(e: any) {
    const form = e?.params?.$form || e.$form;
    const property = e?.params?.property || e.property;
    // 单据暂时关闭“enter”回调（仅表单）
    // window.addEventListener('keydown', this.listenEnter);
    for (let i = 0; i < form.$children.length; i++) {
      // if (!Tsrv.utils.noValue(form.$children[i].$children[0])) {
      if (!Tsrv.utils.noValue(form.$children[i].itemConfig)) {
        const currentColumnEle = form.$children[i];
        if (currentColumnEle.itemConfig.field === property) {
          this.current.columnIndex = i;
          this.current.column = form.$children[i];
          break;
        }
      }
    }
    // this.current.columnIndex = Tsrv.utils.findIndexOf(
    //   form.$children,
    //   el => el.field === property
    // );
    // this.current.column = form.$children[this.current.columnIndex];
    //
    // if (!this.isIndependent) {
    //   this.$emit('on-change', {
    //     index: this.parentID,
    //     data: e,
    //     eventType: 'focus'
    //   });
    // }
  }

  // 监听数据改动
  private listenDoChange(e: any) {
    if (this.isIndependent) {
      let action;
      for (let i = 0; i < e.$form.items.length; i++) {
        if (e.$form.items[i].field === e.property) {
          const attrs = e.$form.items[i].itemRender.attrs;
          if (attrs['actions']) {
            action = attrs['actions'].dochange;
          }
          break;
        }
      }
      if (action) {
        const params = {
          pFuncName: '_sys_p_fieldCalc',
          pCalcField: e.property,
          pData: [
            {
              sTableName: this.name,
              iCalcTable: 1,
              sTableData: e.data
            }
          ]
        };

        Tsrv.httpReqV1.vce(params).then(res => {
          res = res.data;
          if (res.success) {
            Object.keys(res.data.data).forEach(key => {
              if (key.indexOf('.') > -1) {
                const field = key.split('.')[1];
                if (
                  Tsrv.utils.find(this.form.items, el => el.field === field)
                ) {
                  this.setFieldValue(field, res.data.data[key]);
                  this.form.data[field] = res.data.data[key];
                }
              }
            });
          }
        });
      }
    } else {
      this.$emit('on-change', {
        index: this.parentID,
        data: e,
        eventType: 'dochange',
        funName: this.funName,
        tableName: this.name,
        comp: this,
        fromComponent: 'form'
      });
    }
  }

  private listenFieldEvent(e: any, type: string) {
    if (this.isIndependent) {
      let actions = [];
      for (let i = 0; i < e.$form.items.length; i++) {
        if (e.$form.items[i].field === e.property) {
          const attrs = e.$form.items[i].itemRender.attrs;
          if (attrs['actions']) {
            actions = attrs['actions'];
          }
          break;
        }
      }
      if (!Tsrv.utils.noValue(type) && !Tsrv.utils.noValue(actions)) {
        const action = Tsrv.utils.find(
          actions,
          item => item.eventType === type
        );
        if (!Tsrv.utils.noValue(action) && !Tsrv.utils.noValue(action.pubApi)) {
          // const params = {
          //   funName: this.funName,
          //   title: e?.property, //
          //   from: 'fieldEvent',
          //   data: {
          //     [Tsrv.globalVar.fieldName.ID]: e.data.id,
          //     [e.property]: e.data[e.property]
          //   },
          //   // parentID: this.linkParent.rowID || 0
          //   parentID: 0
          // };
          const params = this.Tcmd.getSelectedData();
          params.title = e?.property;
          params.from = 'fieldEvent';
          this.doEvent(action.pubApi, params, { rowData: e });
        }
      }
    } else {
      if (type === 'blur') {
        // window.removeEventListener('keydown', this.listenEnter);
      }
      if (type === 'focus') {
        this.listenFocus(e);
      }
      this.$emit('on-change', {
        index: this.parentID,
        data: e,
        eventType: type,
        funName: this.funName,
        tableName: this.name,
        comp: this,
        fromComponent: 'form'
      });
    }
  }

  /**
   * 监听输入 （暂停使用，后期确认无用后删除）
   */
  private listenInput(e: any) {
    if (!this.isIndependent) {
      this.$emit('on-change', {
        index: this.parentID,
        data: e,
        eventType: 'input'
      });
    }
  }

  /**
   * 监听失去焦点（暂停使用，后期确认无用后删除）
   */
  private listenBlur(e: any) {
    window.removeEventListener('keydown', this.listenEnter);
    if (!this.isIndependent) {
      this.$emit('on-change', {
        index: this.parentID,
        data: e,
        eventType: 'blur'
      });
    }
  }

  /**
   * 监听回车
   */
  private listenEnter(e: any) {
    if (e.key === 'Enter') {
      if (this.current.columnIndex + 1 < this.form.$children.length) {
        const columnList = this.form.$children;
        for (let i = this.current.columnIndex + 1; i < columnList.length; i++) {
          if (!Tsrv.utils.noValue(columnList[i].$children[0])) {
            const nextColumnEle = columnList[i].$children[0];
            if (nextColumnEle.renderOpts.name !== 'oSwitch') {
              nextColumnEle.focus();
              break;
            }
          }
        }
      }
    }
  }

  /**
   * 执行自定义功能
   */
  public doCustomBtnAction(title: string, action: string) {
    // const params = {
    //   funName: this.funName,
    //   title,
    //   from: 'customButton',
    //   data: {}
    // };
    // params.data[this.funName] = Tsrv.utils.clone(this.localData);

    const params = this.Tcmd.getSelectedData();
    params.title = title;
    params.from = 'customButton';

    // vxeConfig
    //   .doCustomBtnAction(title, action, params)
    //   .then(r => {
    //     if (typeof r === 'object') {
    //       const [res, err] = r;
    //       this.$msg(err ?? res.msg);
    //       if (res?.data?.request && res.success) {
    //         this.interactionMsgHandle(res.data.request);
    //         this.loadData();
    //       }
    //     }
    //   })
    //   .catch(err => {
    //     console.error(err);
    //   });
    this.doEvent(action, params);
  }

  // 执行事件
  public doEvent(action: string, params: any, serviceData?: any) {
    return new Promise<boolean>((resove, reject) => {
      Tsrv.doEvent(
        action,
        Tsrv.getFunInfo(this.funName) as ifs.I_funInfo,
        () => params
      )
        .then(r => {
          if (r.isErr()) {
            this.$msg(r.errmsg);
            resove(false);
          } else {
            const res = r.getReturnData('conf');
            if (Tsrv.utils.noValue(res)) {
              return;
            }
            // 0 存储过程  1 系统策略 2 规则库 3 web请求
            if (res.apiType <= 2) {
              this.$msg(res.res.msg);
              // 会话处理
              this.interactionMsgHandle(res.res.data?.request, serviceData);
              // this.loadTableData();
            }
            resove(true);
          }
        })
        .catch(err => {
          console.error(err);
          reject(false);
        });
    });
  }

  /**
   * 上一页
   */
  public prev() {
    if (this.pageNo > 1) {
      vxeConfig.form
        .jumpTo(-1, this.pageNo, this.total, this.toolbar)
        .then((current: number) => {
          this.pageNo = current;
          this.loadData(this.pageNo);
        });
    }
  }

  /**
   * 下一页
   */
  private next() {
    if (this.pageNo !== this.total) {
      vxeConfig.form
        .jumpTo(null, this.pageNo, this.total, this.toolbar)
        .then((current: number) => {
          this.pageNo = current;
          this.loadData(this.pageNo);
        });
    }
  }

  /**
   * 跳页
   */
  public jumpTo(to: number) {
    vxeConfig.form
      .jumpTo(to, this.pageNo, this.total, this.toolbar)
      .then((current: number) => {
        this.pageNo = current;
        this.loadData(this.pageNo);
      });
  }

  /**
   * 尾页
   */
  public end() {
    vxeConfig.form
      .jumpTo(this.total, this.pageNo, this.total, this.toolbar)
      .then((current: number) => {
        this.pageNo = current;
        this.loadData(this.pageNo);
      });
  }

  /**
   * 起始页
   */
  public start() {
    vxeConfig.form
      .jumpTo(1, this.pageNo, this.total, this.toolbar)
      .then((current: number) => {
        this.pageNo = current;
        this.loadData(this.pageNo);
      });
  }

  // 会话消息处理
  public interactionMsgHandle(msg: N_oInteraction.I_msg, serviceData?: any) {
    if (Tsrv.utils.noValue(msg)) {
      return;
    }
    const obj = new ts.T_interaction();
    const res = obj.parseMsg(msg);
    if (res.isErr()) {
      this.$msg(res.errmsg);
    } else {
      const interactionCf = res.getReturnData('conf');
      // 处理 cmd
      switch (interactionCf.cmd) {
        case N_oInteraction.V_cmd.FIELD_EVENT:
          // eslint-disable-next-line no-case-declarations
          const { fieldData } = serviceData;
          this.handleFieldEvent(interactionCf, fieldData);
          break;

        default:
          Tsrv.utils
            .createModal('oInteraction', interactionCf)
            .then(r => {
              this.interactionEventHandle({ resp: r }, msg.next);
            })
            .catch(e => {
              console.error(e);
              this.$msg(e);
            });
          break;
      }
    }
  }

  interactionEventHandle(e: any, next: any = null) {
    if (
      Tsrv.utils.noValue(next) &&
      ((next?.ok && next?.ok?.spName) || (next?.cancel && next?.cancel?.spName))
    ) {
      if (next?.ok && next?.ok?.spName) {
        // this.interactionExecSp('getorderinfo', next.ok.spName, e);
        this.doEvent(next.ok.spName, e);
      } else if (next?.cancel && next?.cancel?.spName) {
        // this.interactionExecSp('getorderinfo', next.cancel.spName, e);
        this.doEvent(next.ok.spName, e);
      }
      if (next?.ok && next?.ok?.actions) {
        this.handleInteractionAcions(next.ok.actions, e);
      } else if (next?.cancel && next?.cancel?.actions) {
        this.handleInteractionAcions(next.cancel.actions, e);
      }
    } else {
      // this.interactionExecSp(
      //   'getorderinfo',
      //   '_sys_interaction_default_resp',
      //   e
      // );
      this.doEvent(next.ok.spName, e);
    }
  }

  private interactionExecSp(title: string, spName: string, params: any) {
    vxeConfig
      // .doCustomBtnAction('getorderinfo', '_sys_interaction_default_resp', e)
      // .then(r => {
      .doCustomBtnAction(title, spName, params, true)
      .then(r => {
        if (typeof r === 'object') {
          const [res, err] = r;
          this.$msg(err ?? res.msg);
          if (res?.data?.request && res.success) {
            this.interactionMsgHandle(res.data.request);
            // this.GT_editor.loadTableData();
          }
        }
      })
      .catch(err => {
        console.error(err);
      });
  }

  // 处理交互消息 确认/取消 后动作
  private handleInteractionAcions(actions: object, e: any) {
    Object.keys(actions).forEach(key => {
      switch (key) {
        case 'isRefresh':
          this.commitEvent('reload');
          break;
        default:
          break;
      }
    });
  }

  // 处理字段事件
  private handleFieldEvent(res: any, fieldInfo: any) {
    const updFields = res['updFields'];
    const fieldsStatus = res['fieldsStatus'];
    if (!Tsrv.utils.noValue(updFields)) {
      Object.keys(updFields).forEach(key => {
        if (key.indexOf('.') > -1) {
          const field = key.split('.')[1];
          this.setFieldValue(field, updFields[key]);
          fieldInfo.data.$form.data[field] = updFields[key];
        }
      });
    }

    // 字段的禁用状态
    if (!Tsrv.utils.noValue(fieldsStatus)) {
      Object.keys(fieldsStatus).forEach(item => {
        if (item.indexOf('.') > -1) {
          const field = item.split('.')[1];
          const targetField = Tsrv.utils.find(
            this.formColumns,
            // it => it.field === field
            it => it.title === field
          );
          if (!Tsrv.utils.noValue(targetField.itemRender.props)) {
            targetField.itemRender.props.disabled = fieldsStatus[item];
          }
        }
      });
    }
  }

  // 给vxe-form 样式设置 js 变量
  private setVxeFormStyleVariable() {
    const formEl = (this.form as Vue).$el;
    if (this.adaptivelayout) {
      formEl['style'].setProperty(
        '--vxe-form--item-width',
        this.adaptivelayout
      );
    }
  }
}
</script>
<style scoped lang="scss">
.panel-form ::v-deep {
  .base-form-toolbar {
    background-color: #fff;
  }
  .vxe-form {
    padding: 20px 0;
    max-width: 1000px;
    min-height: calc(100% - 60px);
    margin: 10px auto;
    box-shadow: var(--default-box-shadow-down);
  }
  .vxe-form--item {
    height: 64px;
  }

  .vxe-form--item-inner {
    flex-direction: column;
    align-items: start;
  }
  .vxe-form--item-content {
    width: 100%;
  }
}

::v-deep .is-adaption {
  .vxe-form--item {
    width: var(--vxe-form--item-width);
  }
}

.main {
  height: 100%;
  background-color: #fff;
  overflow: hidden;
  &.is--max {
    width: 100%;
    left: 0;
    top: 0;
    z-index: 1000;
    position: fixed;
  }
  .wy-grid {
    padding-bottom: 10px;
  }
}
.panel-content {
  height: 100%;

  .panel-form {
    background-color: #f1f1f1;
  }
}
.panel-search {
  height: 100%;
  z-index: 1;
  .panel-search-header {
    position: absolute;
    top: 4px;
    z-index: 3;
    background-color: #fff;
  }
  .panel-search-result {
    height: 100%;
  }
}
.panel-split ::v-deep {
  .right-pane {
    z-index: 4;
  }
}
</style>
